﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Kgb.Model.Models;
using Kgb.Service.Repository;
using Kgb.Service.Repository.Interface;
using System.Net;

namespace Kgb.Service.Controllers
{
    public class LocationsController : ApiController
    {
        //static readonly
        private ILocationRepository _repository = new LocationRepository();

        public LocationsController()
        { 
            _repository = new LocationRepository();
        }

        public IQueryable<Location> GetAllLocations()
        {
            return _repository.GetAll();
        }
                        
        public Location GetLocation(int id)
        {
            Location location = _repository.Get(id);
            if (location == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return location;
        }

        [HttpGet]
        public Player Player(int id, int getPlayer)
        {
            Location location = _repository.Get(id);
            if (location == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }


            if (location.LocationPlayer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            return location.LocationPlayer;
        }

        public HttpResponseMessage<Location> PostLocation(Location location)
        {
            location = _repository.Add(location);
            var response = new HttpResponseMessage<Location>(location, HttpStatusCode.Created);

            string uri = Url.Route(null, new { id = location.Id });
            response.Headers.Location = new Uri(Request.RequestUri, uri);
            return response;
        }

        public void PutLocation(int id, Location location)
        {
            location.Id = id;
            if (!_repository.Update(location))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public HttpResponseMessage DeleteLocation(int id)
        {
            _repository.Remove(id);
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
}